import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:photo_view/photo_view.dart';
import 'package:photo_view/photo_view_gallery.dart';
import 'dart:io';

const Color _selColor = Colors.white;
const Color _otherColor = Colors.grey;

class FadeRoute extends PageRouteBuilder {
  final Widget? page;

  FadeRoute({this.page})
      : super(
          pageBuilder: (
            BuildContext context,
            Animation<double> animation,
            Animation<double> secondaryAnimation,
          ) =>
              page!,
          transitionsBuilder: (
            BuildContext context,
            Animation<double> animation,
            Animation<double> secondaryAnimation,
            Widget child,
          ) =>
              FadeTransition(
            opacity: animation,
            child: child,
          ),
        );
}

class ImagePreview extends StatefulWidget {
  final List<String> imgDataArr;
  final List<String> thumbDataArr;
  final int index;
  final String? heroTag;
  final PageController? controller;
  final void Function(int index, String url)? onLongPress;

  const ImagePreview({
    super.key,
    required this.imgDataArr,
    this.thumbDataArr = const [],
    this.index = 0,
    this.onLongPress,
    this.controller,
    this.heroTag,
  }) : assert(index >= 0 && index < imgDataArr.length,
            'initialIndex must be within imgDataArr bounds');

  @override
  ImagePreviewState createState() => ImagePreviewState();
}

class ImagePreviewState extends State<ImagePreview> {
  int currentIndex = 0;
  late final PageController _pageController;

  @override
  void initState() {
    super.initState();
    currentIndex = widget.index;
    _pageController =
        widget.controller ?? PageController(initialPage: widget.index);
  }

  @override
  void dispose() {
    // 只销毁自己创建的 controller，避免销毁外部传入的 controller
    if (widget.controller == null) {
      _pageController.dispose();
    }
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      body: Stack(
        children: <Widget>[
          Positioned(
              top: 0,
              left: 0,
              bottom: 0,
              right: 0,
              child: GestureDetector(
                child: Container(
                    color: Colors.black,
                    child: PhotoViewGallery.builder(
                      scrollPhysics: const BouncingScrollPhysics(),
                      builder: (BuildContext buildContext, int index) {
                        ImageProvider imgProvider;
                        if (widget.imgDataArr[index].startsWith("http://") ||
                            widget.imgDataArr[index].startsWith("https://")) {
                          imgProvider = CachedNetworkImageProvider(
                              widget.imgDataArr[index],
                              errorListener: (_) => debugPrint(
                                  "Image load failed! Source: ${widget.imgDataArr[index]}"));
                        } else {
                          imgProvider =
                              FileImage(File(widget.imgDataArr[index]));
                        }
                        return PhotoViewGalleryPageOptions(
                          imageProvider: imgProvider,
                          heroAttributes: widget.heroTag != null
                              ? PhotoViewHeroAttributes(tag: widget.heroTag!)
                              : null,
                          initialScale: PhotoViewComputedScale.contained * 1,
                          // 默认倍数
                          minScale: PhotoViewComputedScale.contained * 1,
                          // 最小缩放倍数
                          maxScale:
                              PhotoViewComputedScale.covered * 2.5, // 最大缩放倍数
                        );
                      },
                      loadingBuilder: (context, event) {
                        // 显示加载进度
                        bool eventNotNull =
                            (event != null && event.expectedTotalBytes != null);
                        if (eventNotNull) {
                          debugPrint(
                              '进度---${(event.cumulativeBytesLoaded / event.expectedTotalBytes!.toDouble())}');
                        }

                        // 添加进度动画+缩略图
                        return Stack(
                            alignment: Alignment.center,
                            children: <Widget>[
                              CachedNetworkImage(
                                imageUrl: widget.thumbDataArr[currentIndex],
                              ),
                              eventNotNull
                                  ? CircularProgressIndicator(
                                      color: Colors.white70,
                                      value: (event.cumulativeBytesLoaded /
                                          event.expectedTotalBytes!.toDouble()),
                                    )
                                  : const SizedBox.shrink(),
                            ]);
                      },
                      itemCount: widget.imgDataArr.length,
                      // loadingChild: SizedBox.shrink(),
                      backgroundDecoration: null,
                      pageController: _pageController,
                      // enableRotation: true,  // 启用旋转
                      onPageChanged: (index) {
                        setState(() {
                          currentIndex = index;
                        });
                      },
                    )),
                onTap: () {
                  Navigator.of(context).pop();
                },
                // onLongPress: widget.onLongPress,
                onLongPress: () {
                  widget.onLongPress!(
                      currentIndex, widget.imgDataArr[currentIndex]);
                },
              )),
          Positioned(
            top: MediaQuery.of(context).padding.top + 30,
            width: MediaQuery.of(context).size.width,
            child: Center(
              child: Text("${currentIndex + 1}/${widget.imgDataArr.length}",
                  style: const TextStyle(color: Colors.white, fontSize: 16)),
            ),
          ),
          Positioned(
            right: 10,
            top: MediaQuery.of(context).padding.top + 15,
            child: IconButton(
              icon: const Icon(Icons.close, size: 30, color: Colors.white),
              onPressed: () {
                Navigator.of(context).pop();
              },
            ),
          ),
          SafeArea(
              child: Align(
                  alignment: Alignment.bottomCenter,
                  child: SizedBox(
                    width: widget.imgDataArr.length >= 6
                        ? 200
                        : widget.imgDataArr.length < 3
                            ? 50
                            : 100,
                    height: widget.imgDataArr.length == 1 ? 0 : 50,
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.spaceAround,
                      children: List.generate(
                        widget.imgDataArr.length,
                        (i) => GestureDetector(
                          child: CircleAvatar(
                            radius: 5.0,
                            backgroundColor:
                                currentIndex == i ? _selColor : _otherColor,
                          ),
                        ),
                      ).toList(),
                    ),
                  )))
        ],
      ),
    );
  }
}
